﻿using System.Threading.Tasks;
using System;
using Microsoft.EntityFrameworkCore;
using Oracle.ManagedDataAccess.Client;
using Microsoft.AspNetCore.Http;
using Simple.Services.System;
using Simple.Services.System.QHSEUser.Models;
using Simple.Services.System.QHSEViolationCategory.Models;

namespace Simple.Services;

public class QHSEPositionService
{
    private readonly SimpleDbContext _context;
    public QHSEPositionService(SimpleDbContext context)
    {
        _context = context;
    }
    public async Task<List<QHSEPositionModel>> GetAsync()
    {
        var keyWorkTypes = await _context.Set<QHSESysPosition>().AsNoTracking().ToListAsync();
        return MapperHelper.Map<List<QHSEPositionModel>>(keyWorkTypes);
    }
    public async Task<string> GetCodeByItemAsync(string item)
    {
        var id = await _context.Set<QHSESysPosition>().AsNoTracking().Where(u=>u.Position.Equals(item)).Select(u=>u.PositionCode).FirstOrDefaultAsync();
        return id;
    }
    public async Task<PageResultModel<QHSEPositionModel>> GetPageAsync(QHSEPositionPageInputModel input)
    {
        var result = new PageResultModel<QHSEPositionModel>();
        var query = _context.Set<QHSESysPosition>().AsNoTracking().AsQueryable();

        if (!string.IsNullOrEmpty(input.Code))
        {
            if (input.Code == "SP1014" || input.Code == "SP1013" || input.Code == "SP1015")
            {
                var allPositions = await _context.Set<QHSESysPosition>().GroupBy(u => u.Position)
                    .Select(group => group.First())
                    .ToListAsync(); ;
                result.Rows = MapperHelper.Map<List<QHSEPositionModel>>(allPositions);
                result.SetPage(input);
                result.CountTotalPage(); 
                MapperHelper.Map<List<QHSEPositionModel>>(allPositions);
                return result;
            }
            query = query.Where(u => EF.Functions.Like(u.SpecialtyCode, $"%{input.Code}%"));

        }
        // 获取总数量
        result.TotalRows = await query.CountAsync();

        // 分页查询
        input.PageSize = result.TotalRows;
        query = query.OrderBy(u => u.OrderNo).Page(input.PageNo, input.PageSize);
        var keyWorkTypes = await query.ToListAsync();
        result.Rows = MapperHelper.Map<List<QHSEPositionModel>>(keyWorkTypes);

        result.SetPage(input);
        result.CountTotalPage();

        return result;
    }
}
